import {
  fieldsToShowList,
  getFilterExpressionBySelected,
  getMergeFilterExpression,
} from './entities';

export default class TagFilterPresenter {
  selectedCodeList = new Set();
  list = [
    // { name: '',code: '', tip:''},
  ];
  fields = [];

  constructor(fields) {
    if (fields) this.init(fields);
  }

  init(fields) {
    this.fields = fields;
    this.list = fieldsToShowList(fields);
    this.selectedCodeList = new Set();
  }

  shiftSelectTag(code) {
    const { selectedCodeList } = this;
    if (selectedCodeList.has(code)) {
      this.cancelSelectTag(code);
    } else {
      this.selectTag(code);
    }
  }
  selectTag(code) {
    this.selectedCodeList.add(code);
  }
  cancelSelectTag(code) {
    this.selectedCodeList.delete(code);
  }

  setSelectedCodeList(codeList = []) {
    this.selectedCodeList.clear();
    codeList.forEach(c => {
      if (this.list.some(({ code }) => code === c)) {
        this.selectedCodeList.add(c);
      }
    });
  }

  getSelectedCodeList() {
    return [...this.selectedCodeList];
  }

  // 外部调用：获取合并后丶过滤条件
  getFilterExpression(advancedFilter) {
    const tagFilter = getFilterExpressionBySelected(
      this.fields,
      this.selectedCodeList,
    );
    return getMergeFilterExpression(tagFilter, advancedFilter);
  }

  getFilterExpressionString(AdvanceFilter) {
    return JSON.stringify(
      this.getFilterExpression(AdvanceFilter) || {
        ElementType: 'Group',
        Filters: [],
      },
    );
  }
}
